package uno.linze.interview_question.util.base;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uno.linze.interview_question.mapper.UserMapper;

import java.security.Key;
import java.util.Date;


@Service
public class JwtUtil {
    @Autowired
    private static UserMapper userMapper;


    public static final String SECRET = "abcdefghijklmnopqrstuvwxyz1234567890"; // 最少32位
    public static final Key KEY = Keys.hmacShaKeyFor(SECRET.getBytes());
    private static final long EXPIRATION_TIME = 86400000; // 24小时

    // 生成令牌
    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(KEY)
                .compact();
    }

    // 从令牌中解析用户名
    public static String getUsernameFromToken(String token) {
        ;

        return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }


    // 验证令牌
    public static boolean validateToken(String token, String username) {
        String extractedUsername = getUsernameFromToken(token);
        return extractedUsername.equals(username) && !isTokenExpired(token);
    }

    // 检查令牌是否过期
    private static boolean isTokenExpired(String token) {
        Date expiration = Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getExpiration();
        return expiration.before(new Date());
    }
}
